import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 03010570
 * @date 2020/07/09
 * describe:    LeetCode : 77、组合    https://leetcode-cn.com/problems/combinations/
 */
public class LeetCode_77 {

    public static void main(String[] args) {
        LeetCode_77 code77 = new LeetCode_77();
        List<List<Integer>> combine = code77.combine2(4, 2);
        for (List<Integer> integers : combine) {
            for (Integer integer : integers) {
                System.out.print(integer + " , ");
            }
            System.out.println();
        }
    }

    public List<List<Integer>> combine2(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            temp.add(0);
        }
        int index = 0;
        while (index >= 0) {
            temp.set(index, temp.get(index) + 1);
            if (temp.get(index) > n) {
                index--;
            } else if (index == k - 1) {
                result.add(new ArrayList<>(temp));
            } else {
                index++;
                temp.set(index, temp.get(index - 1));
            }
        }
        return result;
    }


    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> outList = new ArrayList<>();
        List<Integer> inList = new ArrayList<>();
        combineFunction(1, n, k, inList, outList);
        return outList;
    }

    private void combineFunction(int start, int n, int k, List<Integer> inList, List<List<Integer>> outList) {
        if (inList.size() == k) {
            outList.add(new ArrayList<>(inList));
            return;
        }
        for (int i = start; i <= n - (k - inList.size()) + 1; i++) {
            inList.add(i);
            combineFunction(i + 1, n, k, inList, outList);
            inList.remove(inList.size() - 1);
        }
    }

}
